import turtle
import random

# 设置游戏窗口
wn = turtle.Screen()
wn.title("躲避障碍物小游戏")
wn.bgcolor("lightblue")
wn.setup(width=800, height=600)
wn.tracer(0)

# 创建玩家角色
player = turtle.Turtle()
player.shape("square")
player.color("blue")
player.penup()
player.goto(0, -250)
player.speed(0)

# 定义玩家移动函数
def move_left():
    x = player.xcor()
    if x > -380:
        x -= 20
    player.setx(x)

def move_right():
    x = player.xcor()
    if x < 380:
        x += 20
    player.setx(x)

# 键盘绑定
wn.listen()
wn.onkeypress(move_left, "Left")
wn.onkeypress(move_right, "Right")

# 创建障碍物列表
obstacles = []

# 生成障碍物
def create_obstacle():
    obstacle = turtle.Turtle()
    obstacle.shape("square")
    obstacle.color("red")
    obstacle.penup()
    x = random.randint(-380, 380)
    obstacle.goto(x, 280)
    obstacle.speed(0)
    obstacles.append(obstacle)

# 移动障碍物
def move_obstacles():
    """
    移动所有障碍物的函数。
    遍历障碍物列表中的每个障碍物，将其垂直向下移动一定距离。
    """
    # 遍历障碍物列表
    for obstacle in obstacles:
        # 获取当前障碍物的 y 坐标
        y = obstacle.ycor()
        # 减少 y 坐标，使障碍物向下移动
        y -= 2
        # 更新障碍物的 y 坐标
        obstacle.sety(y)


# 碰撞检测
def is_collision(t1, t2):
    distance = t1.distance(t2)
    if distance < 20:
        return True
    else:
        return False

# 主游戏循环
while True:
    wn.update()

    # 每隔一段时间生成一个障碍物
    if random.randint(1, 100) < 2:
        create_obstacle()

    move_obstacles()

    # 检查碰撞
    for obstacle in obstacles:
        if is_collision(player, obstacle):
            print("游戏结束！")
            wn.bye()
            break

    # 移除超出屏幕的障碍物
    for obstacle in obstacles[:]:
        if obstacle.ycor() < -300:
            obstacles.remove(obstacle)